/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-07-24
*/
package com.rzico.order.service;

import com.alibaba.fastjson.JSON;
import com.rzico.account.entity.Payment;
import com.rzico.account.entity.Point;
import com.rzico.account.entity.Refunds;
import com.rzico.account.model.Attach;
import com.rzico.account.service.PaymentService;
import com.rzico.account.service.RefundsService;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.Card;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Product;
import com.rzico.basics.service.MemberService;
import com.rzico.basics.service.MsgService;
import com.rzico.basics.service.ProductService;
import com.rzico.exception.CustomException;
import com.rzico.order.entity.Order;
import com.rzico.order.entity.OrderItem;
import com.rzico.order.entity.VirtualProduct;
import com.rzico.order.entity.VirtualStock;
import com.rzico.order.mapper.OrderMapper;
import com.rzico.order.mapper.VirtualProductMapper;
import com.rzico.order.model.VirtualStockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.rzico.order.mapper.VirtualStockMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 虚拟商品库存业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class VirtualStockService extends BaseServiceImpl<VirtualStock, String> {

    @Autowired
    private VirtualStockMapper virtualStockMapper;

    @Autowired
    private VirtualProductMapper virtualProductMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private RefundsService refundsService;

    @Autowired
    private ProductService productService;

    @Autowired
    private MemberService memberService;

    @Autowired @Lazy
    private MsgService msgService;

    @Override
    public BaseMapper<VirtualStock, String> getMapper() {
        return virtualStockMapper;
    }

    public List<VirtualStockVo> selectVoList(Map<String, Object> params) {
        return virtualStockMapper.selectVoList(params);
    }

    //付款
    @Transactional(rollbackFor = Exception.class)
    public void payment(Payment payment) {

        if (!payment.getStatus().equals(Payment.STATUS_WAITING)) {
            throw new CustomException("不是待付款状态");
        }

        payment.setStatus(Payment.STATUS_SUCCESS);
        payment.setPaymentDate(new Date());
        paymentService.updateByPrimaryKeySelective(payment);

        Attach attach = payment.decodeAttach();

        VirtualStock virtualStock = virtualStockMapper.selectByPrimaryKey(attach.getCardId());

        BigDecimal value = attach.getQuantity();

        if (virtualStock.getStock().compareTo(value)<0) {
            throw new CustomException("余票不足");
        }

        Order order = orderMapper.selectByPrimaryKey(attach.getId());

        Product product = productService.findById(virtualStock.getProductId());

        BigDecimal price = payment.getAmount().divide(virtualStock.getStock(),2,BigDecimal.ROUND_HALF_DOWN);
        BigDecimal cost = product.getCost().divide(virtualStock.getStock(),2,BigDecimal.ROUND_HALF_DOWN);

        Map<String,Object> params = new HashMap<>();
        params.put("id",virtualStock.getId());
        params.put("price",price.multiply(value));
        params.put("cost",cost.multiply(value));
        params.put("stock",value);
        virtualStockMapper.decStock(params);

        virtualStock = virtualStockMapper.selectByPrimaryKey(virtualStock.getId());

        if (virtualStock.getStock().compareTo(BigDecimal.ZERO)<0) {
            throw new CustomException("余票不足");
        }

        value = BigDecimal.ZERO.subtract(value);
        VirtualProduct virtualProduct = new VirtualProduct();
        virtualProduct.setVirtualStockId(virtualStock.getId());
        virtualProduct.setCost(cost.multiply(value));
        virtualProduct.setCreateDate(new Date());
        virtualProduct.setDiscount(BigDecimal.ZERO);
        virtualProduct.setQuantity(value);
        virtualProduct.setMemberId(payment.getMemberId());
        virtualProduct.setPrice(price.multiply(value));
        virtualProduct.setEnterpriseId(payment.getEnterpriseId());
        virtualProduct.setOrderId(Long.parseLong(attach.getId()));
        virtualProduct.setOrderSn(order.getSn());
        virtualProduct.setName(product.getName());
        virtualProduct.setSpec(product.getSpec());
        virtualProduct.setThumbnail(product.getThumbnail());
        virtualProduct.setUnit(product.getUnit());
        virtualProduct.setVirtualType(3);
        virtualProduct.setSubType(product.getSubType());
        virtualProduct.setSn(product.getSn());
        virtualProduct.setProductId(product.getId());
        virtualProductMapper.insertUseGeneratedKeys(virtualProduct);

        Map<String,Object> content = new HashMap<>();
        content.put("title", "付款成功-电子水票");
        content.put("memo",payment.getMemo());
        content.put("amount",payment.getAmount());
        content.put("balance",virtualStock.getStock());
        content.put("type",3);
        Member member = memberService.selectByPrimaryKey(payment.getMemberId());
        msgService.sendNotity(member,"msg-account",content.get("title").toString(), JSON.toJSONString(content),null);


    }

    //退款
    @Transactional(rollbackFor = Exception.class)
    public void refunds(Refunds refunds) {
        if (!refunds.getStatus().equals(Refunds.STATUS_WAITING)) {
            throw new CustomException("不是待退款状态");
        }
        refunds.setStatus(Refunds.STATUS_REFUNDED);
        refunds.setRefundsDate(new Date());
        refundsService.updateByPrimaryKeySelective(refunds);

        Attach attach = refunds.decodeAttach();

        VirtualStock virtualStock = virtualStockMapper.selectByPrimaryKey(attach.getCardId());

        //TODO 水票支付时，退几张水票按金额比例分滩，现在只支持全退

        BigDecimal value = attach.getQuantity();

        Product product = productService.findById(virtualStock.getProductId());
        Order order = orderMapper.selectByPrimaryKey(attach.getId());

        BigDecimal price = refunds.getAmount().divide(value,2,BigDecimal.ROUND_HALF_DOWN);
        BigDecimal cost = product.getCost().divide(value,2,BigDecimal.ROUND_HALF_DOWN);

        Map<String,Object> params = new HashMap<>();
        params.put("id",virtualStock.getId());
        params.put("price",price.multiply(value));
        params.put("cost",cost.multiply(value));
        params.put("stock",value);
        virtualStockMapper.addStock(params);

        VirtualProduct virtualProduct = new VirtualProduct();
        virtualProduct.setVirtualStockId(virtualStock.getId());
        virtualProduct.setCost(cost.multiply(value));
        virtualProduct.setCreateDate(new Date());
        virtualProduct.setDiscount(BigDecimal.ZERO);
        virtualProduct.setQuantity(value);
        virtualProduct.setMemberId(refunds.getMemberId());
        virtualProduct.setPrice(price.multiply(value));
        virtualProduct.setEnterpriseId(refunds.getEnterpriseId());
        virtualProduct.setOrderId(Long.parseLong(attach.getId()));
        virtualProduct.setOrderSn(order.getSn());
        virtualProduct.setName(product.getName());
        virtualProduct.setSpec(product.getSpec());
        virtualProduct.setThumbnail(product.getThumbnail());
        virtualProduct.setUnit(product.getUnit());
        virtualProduct.setVirtualType(3);
        virtualProduct.setSubType(product.getSubType());
        virtualProduct.setSn(product.getSn());
        virtualProduct.setProductId(product.getId());
        virtualProductMapper.insertUseGeneratedKeys(virtualProduct);

        Map<String,Object> content = new HashMap<>();
        content.put("title", "退款成功-电子水票");
        content.put("memo",refunds.getMemo());
        content.put("amount",refunds.getAmount());
        content.put("balance",virtualStock.getStock());
        content.put("type",3);
        Member member = memberService.selectByPrimaryKey(refunds.getMemberId());
        msgService.sendNotity(member,"msg-account",content.get("title").toString(), JSON.toJSONString(content),null);

    }

    //我的所有电子水票
    public List<VirtualStock> findByMember(Long memberId) {
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",memberId);
        return virtualStockMapper.selectList(params);
    }


    public BigDecimal selectStockSum(Long enterpriseId,Long memberId,Integer subType) {
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",memberId);
        params.put("enterpriseId",enterpriseId);
        params.put("subType",subType);
        BigDecimal amount = virtualStockMapper.selectStockSum(params);
        if (amount==null) {
            return BigDecimal.ZERO;
        } else {
            return amount;
        }
    }

    public BigDecimal selectPriceSum(Long enterpriseId,Long memberId,Integer subType) {
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",memberId);
        params.put("enterpriseId",enterpriseId);
        params.put("subType",subType);
        BigDecimal amount = virtualStockMapper.selectPriceSum(params);
        if (amount==null) {
            return BigDecimal.ZERO;
        } else {
            return amount;
        }
    }


}
